<?php

class Model_MailSubscriptions extends RL_Model
{
	protected function init()
	{
		$this->store = $this->ctx->store;

		$emails = $this->ctx->td->new_inst('cemails');
		$emails->store = $this->ctx->store;
		$this->emails = $emails;

		$subscribers = $this->ctx->td->new_inst('csubscribers');
		$subscribers->store = $this->ctx->store;
		$this->subscribers = $subscribers;
	}

	public function selectNotifyComments ($item)
	/**
	 * Выбрать подписчиков для уведомления о новом комменте.
	 *
	 * Выбираем:
	 *   которые участвовали в дискусси про $item (постили комменты);
	 *   автора $item'а;
	 * исключая автора коммента (ticket#201).
	 *
	 * @param mixed $item <{}>
	 * @access public
	 * @return void
	 */
	{
		$prefix     = $this->store->db->db_prefix;
		$item_oid   = $this->store->db->quote($item->id);
		$poster_oid = $this->store->db->quote($item->data['posted_by_id']);
		$parent_oid = 0;
		if ( isset($item->parent) && isset($item->parent->id) ) {
			$parent_oid = $this->store->db->quote($item->parent->id);
		}

		$sql = "
        SELECT DISTINCT `{$prefix}objects`.*
        FROM `{$prefix}objects`
          INNER JOIN `{$prefix}class_subscribers` ON (`{$prefix}class_subscribers`.oid = `{$prefix}objects`.oid)
          INNER JOIN `{$prefix}class_emails`      ON (`{$prefix}class_emails`.user_oid = `{$prefix}objects`.oid)
          INNER JOIN `{$prefix}class_comment`     ON (
                                                      `{$prefix}class_comment`.posted_by_id = `{$prefix}objects`.oid
                                                  AND `{$prefix}class_comment`.item_oid = {$item_oid}
                                                  )
        WHERE (`{$prefix}class_subscribers`.`topic_oid` = '2')
          AND (`{$prefix}objects`.oid <> {$poster_oid})

        UNION DISTINCT

        SELECT DISTINCT `{$prefix}objects`.*
        FROM `{$prefix}objects`
          INNER JOIN `{$prefix}class_subscribers` ON (`{$prefix}class_subscribers`.oid = `{$prefix}objects`.oid)
          INNER JOIN `{$prefix}class_emails`      ON (`{$prefix}class_emails`.user_oid = `{$prefix}objects`.oid)
          INNER JOIN `{$prefix}class_allfeed`     ON (
                                                      `{$prefix}class_allfeed`.oid = {$item_oid}
                                                  AND `{$prefix}class_allfeed`.posted_by_id = `{$prefix}objects`.oid
                                                  )
        WHERE (`{$prefix}class_subscribers`.`topic_oid` = '2')
          AND (`{$prefix}objects`.oid <> {$poster_oid})
		";

		if ( $parent_oid ) {
		$sql .= "
        UNION DISTINCT

        SELECT DISTINCT `{$prefix}objects`.*
        FROM `{$prefix}objects`
          INNER JOIN `{$prefix}class_subscribers` ON (`{$prefix}class_subscribers`.oid = `{$prefix}objects`.oid)
          INNER JOIN `{$prefix}class_emails`      ON (`{$prefix}class_emails`.user_oid = `{$prefix}objects`.oid)
          INNER JOIN `{$prefix}class_comment`     ON (
                                                      `{$prefix}class_comment`.posted_by_id = `{$prefix}objects`.oid
                                                  AND `{$prefix}class_comment`.item_oid = {$item_oid}
                                                  )
        WHERE (`{$prefix}class_subscribers`.`topic_oid` = '2')
          AND (`{$prefix}objects`.oid = {$parent_oid})
		";
		}
		return $this->subscribers->selectSQL($sql);
	} // end of method selectNotifyComments
	public function selectNotifyItems ($community_oid)
	/**
	 * Выбрать подписчиков для уведомления о новом item'е.
	 *
	 * @access public
	 * @return void
	 */
	{
		$prefix = $this->store->db->db_prefix;
		$community_oid_sql  = $this->store->db->quote($community_oid);
		$sql = "
        SELECT DISTINCT `{$prefix}objects`.*
        FROM `{$prefix}objects`
          INNER JOIN `{$prefix}class_subscribers` ON (`{$prefix}class_subscribers`.oid = `{$prefix}objects`.oid)
          INNER JOIN `{$prefix}class_emails`      ON (`{$prefix}class_emails`.user_oid = `{$prefix}objects`.oid)
          INNER JOIN `{$prefix}class_member`      ON (`{$prefix}class_member`.user_oid = `{$prefix}objects`.oid AND `{$prefix}class_member`.community_oid = $community_oid_sql)
        WHERE (`{$prefix}class_subscribers`.`topic_oid` = '1')
		";
		return $this->subscribers->selectSQL($sql);
	} // end of method select

	public function subscribe ($user, $topic)
	/**
	 * Подписать пользователя на рассылку.
	 *
	 * @param fuser $user пользователь
	 * @param integer $topic идентификатор подписки:
	 *                         '1' подписка на selectNotifyItems()
	 *                         '2' подписка на selectNotifyComments()
	 * @access public
	 * @return boolean
	 */
	{
		$status = false;
		$this->store->db->begin();
		if (isset($user->data['email']) && $this->validate_email($user->data['email'])) {
			$email_address = $user->data['email'];
			$email = $this->emails->get('select objects where emails.email = :0', array($email_address));
			if (is_null($email)) {
				$email = $this->store->create('femail', array(
					'user_oid' => $user->id,
					'email' => $email_address,
				));
        $email->save();
				$this->emails->add($email);
				$status = true;
			}
		}
		$this->subscribers->replace(array('oid'=>$user->id, 'email_oid'=>$email->id, 'topic_oid'=>$topic));
		$this->store->db->end();
		return $status;
	} // end of method subscribe
	public function unsubscribe ($user, $topic)
	/**
	 * Отписать пользователя от рассылки.
	 *
	 * @param fuser $user пользователь
	 * @param integer $topic идентификатор подписки:
	 *                         '1' подписка на selectNotifyItems()
	 *                         '2' подписка на selectNotifyComments()
	 * @access public
	 * @return boolean
	 */
	{
		$status = false;
		$this->store->db->begin();
		if (isset($user->data['email']) && $this->validate_email($user->data['email'])) {
			$email_address = $user->data['email'];
			$email = $this->emails->get('select objects where emails.email = :0', array($email_address));
			$this->subscribers->delete(array('oid'=>$user->id, 'email_oid'=>$email->id, 'topic_oid'=>$topic));
			$status = true;
		}
		$this->store->db->end();
		return $status;
	} // end of method subscribe


	public function validate_email ($v)
	{
		if (!empty($v)) return true;
		return false;
	} // end of method validate_email
}
